﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    /// <summary>
    /// 客制程序，客户箱规修改
    /// </summary>
    /// 
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P58E4203Controller : ControllerBase
    {

        /// <summary>
        /// 客户箱规更新，如果查询不存在，则新增
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> Clientpackage_Update(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string clientnumber = objpram["clientnumber"].ToString();
            string itemnumber = objpram["itemnumber"].ToString();
            int clientpackage = (int)objpram["clientpackage"];
            int standpackage = (int)objpram["standpackage"];

            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                //OAuthController oAuth = new OAuthController();
                //oAuth.GetToken(objpram);
                //if (string.IsNullOrWhiteSpace(SomeHandler.GetToken(username,password)))
                //{
                //    throw new Exception("验证失败，请检查用户名密码是否正确！");
                //}
                string token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }


                Log4Net.Debug($"{username}查询客户箱规{clientnumber}{clientpackage}");
                int stackId = 0;
                int stateId = 0;
                string rid = "";

                Console.WriteLine($"username:{username} Token:{token}");

                FormRequest formRequest = new FormRequest()
                {
                    maxPageSize = "5",
                    returnControlIDs = "1[20,21,22,23]",
                    formName = "P58E4203_W58E4203A",
                    version = "",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                    ,
                    formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                        new FSREvent() { controlID="1[20]", command="SetQBEValue" ,value=clientnumber },
                                        new FSREvent() { controlID="1[21]", command="SetQBEValue",value=itemnumber },
                                        new FSREvent() { controlID="15", command="DoAction"  }
                                      }
                                  )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P58E4203_W58E4203A",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                };
                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                Log4Net.Debug(response.JsonString);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    int rowcount = Convert.ToInt16(obj["fs_P58E4203_W58E4203A"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"客户箱规修改-查询出数据{rowcount}条");
                    if (rowcount > 0)
                    {
                        stackId = response.stackId;
                        stateId = response.stateId;
                        Console.WriteLine("客户箱规修改-选择查询出的数据");

                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[17,18,19,20]",
                            formOID = "W58E4203A",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                          new FSREvent() { controlID="1.0", command="SelectRow"   },
                                          new FSREvent() { controlID="14", command="DoAction"  }
                                      }
                                  )
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        //Console.WriteLine(response.JsonString);
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203C"))
                        {
                            Console.WriteLine("客户箱规修改-填入修改后的值");
                            stackId = response.stackId;
                            stateId = response.stateId;
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                            gridcols.Add(new gridcolumnevent()
                            {
                                columnID = "19",
                                command = "SetGridCellValue",
                                value = clientpackage.ToString()
                            });
                            gridcols.Add(new gridcolumnevent()
                            {
                                columnID = "20",
                                command = "SetGridCellValue",
                                value = standpackage.ToString()
                            });
                            gridrows.Add(new gridrowupdateevents() { gridColumnEvents = gridcols, rowNumber = 0 });

                            actionRequest = new ActionRequest()
                            {
                                returnControlIDs = "1[17,18,19,20]",
                                formOID = "W58E4203C",
                                formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1.0", command="SelectRow" ,gridAction =new GridAction(){
                                          gridID="1",gridRowUpdateEvents=gridrows
                                      } },
                                      new FSREvent() { controlID="12", command="DoAction"  }
                                     }
                                 )
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            execresult.Message = response.JsonString;
                            if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203A"))
                            {
                                actionRequest = new ActionRequest()
                                {
                                    returnControlIDs = "1[19]",
                                    formOID = "W58E4203A"
                                };
                                asrequest = new ApplicationStackRequest()
                                {
                                    outputType = "VERSION2",
                                    allowCache = true,
                                    action = "close",
                                    actionRequest = actionRequest,
                                    stackId = response.stackId,//上一次返回的值
                                    stateId = response.stateId,
                                    rid = response.rid
                                };
                                response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                                //Console.WriteLine(response.JsonString);
                                Console.WriteLine($"{DateTime.Now.ToString()} 修改成功！{clientnumber} { itemnumber} {clientpackage}");
                            }

                        }
                    }
                    else
                    {
                        //此处也需要close上面的app，否则时间长了会把jde搞挂
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[19]",
                            formOID = "W58E4203A"
                        };
                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "close",
                            actionRequest = actionRequest,
                            stackId = response.stackId,//上一次返回的值
                            stateId = response.stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);

                        return Clientpackage_Insert(username, password, clientnumber, itemnumber, clientpackage, standpackage);
                    }
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }

        /// <summary>
        /// 客户箱规新增
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        //[HttpPost]
        private ActionResult<MQResponse> Clientpackage_Insert(string username, string password, string clientnumber, string itemnumber, int clientpackage, int standpackage)
        {
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };


            if (string.IsNullOrWhiteSpace(AISClientHandler.Instance.GetCurrentToken()))
            {
                AISClientHandler.Instance.Token = SomeHandler.GetToken(username, password);
            }


            gridcolumnCollection cols = new gridcolumnCollection();
            cols.Add(new gridcolumnevent() { columnID = "17", value = clientnumber, command = "SetGridCellValue" });
            cols.Add(new gridcolumnevent() { columnID = "18", value = itemnumber, command = "SetGridCellValue" });
            cols.Add(new gridcolumnevent() { columnID = "19", value = clientpackage.ToString(), command = "SetGridCellValue" });
            cols.Add(new gridcolumnevent() { columnID = "20", value = standpackage.ToString(), command = "SetGridCellValue" });
            execresult.Message = AISClientHandler.Instance.Formservice_insert("P58E4203_W58E4203C", "",
                    new FormActionsCollection
                    (
                    ),
                    new List<gridcolumnCollection>()
                {
                    cols
                },
                new FormActionsCollection
                (
                    new FSREvent[]
                    {
                            new FSREvent() { controlID="12", command="DoAction"  }
                    }
                )
                ).JsonString;
            if (CommonHandler.ValidateReturnValue(execresult.Message, "fs_P58E4203_W58E4203C"))
            {
                execresult.ResponseCode = "200";
            }
            return execresult;
        }

        /// <summary>
        /// 客户属性更新，PP OR SS
        /// </summary>
        [HttpPost]
        public ActionResult<MQResponse> ClientUpdate(dynamic objparam)
        {
            Log4Net.Debug(objparam);
            Console.WriteLine(objparam);
            //用了新的方式，哈哈方便多了
            P58E4203param param = Common.JsonHelper.JsonToObject<P58E4203param>(((Newtonsoft.Json.Linq.JObject)objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";

            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }


                Log4Net.Debug($"{param.username}查询客户属性设置{param.clientnumber}  ");
                FormRequest formRequest = new FormRequest()
                {
                    maxPageSize = "5",
                    returnControlIDs = "1[18,19]",
                    formName = "P58E4203_W58E4203D",
                    version = "",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                  ,
                    formActions = new FormActionsCollection
                                (
                                    new FSREvent[]
                                    {
                                        new FSREvent() { controlID="25", command="SetControlValue" ,value=param.clientnumber },
                                        new FSREvent() { controlID="29", command="DoAction"  }
                                    }
                                )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P58E4203_W58E4203D",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                };
                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203D"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    int rowcount = Convert.ToInt16(obj["fs_P58E4203_W58E4203D"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"客户属性修改-查询出数据{rowcount}条");
                    if (rowcount > 0)//存在就修改
                    {
                        Console.WriteLine($"客户属性修改-填入修改后的值{param.clientnumber} {param.clientlttp}");
                        List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                        List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = "19",
                            command = "SetGridCellValue",
                            value = param.clientlttp
                        });
                        gridrows.Add(new gridrowupdateevents() { gridColumnEvents = gridcols, rowNumber = 0 });

                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[18,19]",
                            formOID = "W58E4203D",
                            formActions = new FormActionsCollection
                             (
                                 new FSREvent[]
                                 {
                                      new FSREvent() { controlID="1.0", command="SelectRow" ,gridAction =new GridAction(){
                                          gridID="1",gridRowUpdateEvents=gridrows
                                      } },
                                      new FSREvent() { controlID="12", command="DoAction"  }
                                 }
                             )
                        };
                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = response.stackId,//上一次返回的值
                            stateId = response.stateId,
                            rid = response.rid
                        };

                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        execresult.Message = response.JsonString;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203D"))
                        {
                            Console.WriteLine($"{DateTime.Now.ToString()} 修改成功！{param.clientnumber} {param.clientlttp}");
                        }

                    }
                    else //不存在就新增
                    {
                        Console.WriteLine($"客户属性新增-填入新增的值{param.clientnumber} {param.clientlttp}");
                        List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                        List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = "18",
                            command = "SetGridCellValue",
                            value = param.clientnumber
                        });
                        gridcols.Add(new gridcolumnevent()
                        {
                            columnID = "19",
                            command = "SetGridCellValue",
                            value = param.clientlttp
                        });
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = gridcols });

                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[18,19]",
                            formOID = "W58E4203D",
                            formActions = new FormActionsCollection
                             (
                                 new FSREvent[]
                                 {
                                      new FSREvent() { controlID="1.0", command="SelectRow" ,gridAction =new GridAction(){
                                          gridID="1",gridRowInsertEvents=gridrows
                                      } },
                                      new FSREvent() { controlID="12", command="DoAction"  }
                                 }
                             )
                        };
                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = response.stackId,//上一次返回的值
                            stateId = response.stateId,
                            rid = response.rid
                        };

                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        execresult.Message = response.JsonString;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4203_W58E4203D"))
                        {
                            Console.WriteLine($"{DateTime.Now.ToString()} 新增成功！{param.clientnumber} {param.clientlttp}");
                        }
                    }

                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                //此处也需要close上面的app，否则时间长了会把jde搞挂
                ActionRequest actionRequest = new ActionRequest()
                {
                    returnControlIDs = "1[19]",
                    formOID = "W58E4203A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(SomeHandler.GetToken(param.username, param.password), asrequest);

            }
            return execresult;
        }
       

    }
}